package message

import (
	"api/common"
	"api/pb/message"
	"context"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetMessageListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetMessageListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetMessageListLogic {
	return &GetMessageListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// GetMessageList 获取消息列表
func (l *GetMessageListLogic) GetMessageList(req *types.MessageListRequest) (resp *types.MessageListResponse, err error) {
	// 1. 获取用户标识
	userID, err := common.GetUserIDFromCtx(l.ctx)
	if err != nil {
		return nil, err
	}
	// 2. 获取消息列表
	result, err := l.svcCtx.MessageRPC.GetMessageList(l.ctx, &message.MessageListRequest{
		UserId: userID, ReceiverType: req.ReceiverType, ReceiverId: req.ReceiverID,
		LastMsgId: req.LastMsgID, Limit: req.Limit, Status: req.Status,
	})
	if err != nil {
		return nil, err
	}

	// 3. 转换响应
	resp = &types.MessageListResponse{
		Total: result.Total,
		Data:  make([]*types.MessageInfo, 0, len(result.Data)),
	}
	for _, item := range result.Data {
		resp.Data = append(resp.Data, &types.MessageInfo{
			ID:           item.Id,
			SenderID:     item.SenderId,
			ReceiverType: item.ReceiverType,
			ReceiverID:   item.ReceiverId,
			ContentType:  item.ContentType,
			Content:      item.Content,
			FileName:     item.FileName,
			FileSize:     item.FileSize,
			Status:       item.Status,
			CreateTime:   item.CreateAt,
			UpdateTime:   item.UpdateAt,
		})
	}
	return resp, nil
}
